package tw.asap.plus.ui.fragment;

import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import java.lang.ref.SoftReference;
import java.util.ArrayList;

import tw.asap.plus.R;
import tw.asap.plus.entity.TabShow;
import tw.asap.plus.ui.activity.MainActivity;
import tw.asap.plus.ui.custom.ImageTextButton;
import tw.asap.plus.utils.ScreenUtil;
import tw.asap.plus.utils.Toaster;

/**
 * 首页底部tab
 */
public class HomeTabFragment extends Fragment implements View.OnClickListener {
    private View vCompanyCard;
    private ImageView ivPointCompanyCard;
    private View vMine;

    private ImageView ivPointMe;
    private Fragment currentFragment;
    private SoftReference<Fragment> mineFragment;
    private SoftReference<Fragment> indexFragment;
    private SoftReference<Fragment> marketFragment;
    private MainActivity homeActivity;
    private LinearLayout llMainView;


    private static final int ID_TAB_SAIL = 0x00;
    private static final int ID_TAB_MARKET = 0x01;
    private static final int ID_TAB_MINE = 0x02;
    private static final int ID_TAB_CART = 0x03;

    private int[] ids = new int[]{ID_TAB_SAIL, ID_TAB_MARKET, ID_TAB_MINE, ID_TAB_CART};

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        llMainView = (LinearLayout) inflater.inflate(R.layout.fragment_home_tab, null);
        homeActivity = (MainActivity) getActivity();
        if (homeActivity == null) {
            //// TODO: 15/11/7  
        }
        configTab();
        return llMainView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
       
        
    }

    /**
     * 配置 tab
     */
    private void configTab() {
        LayoutInflater inflater = LayoutInflater.from(homeActivity);
        LinearLayout.LayoutParams paramsLL = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        paramsLL.weight = 1;
        paramsLL.setMargins(0, ScreenUtil.dip2px(getActivity(), 4), 0, ScreenUtil.dip2px(getActivity(), 4));
        int weightSum = 3;
        ArrayList<TabShow> tabShows = getTabShows();
        for (int i = 0; i < tabShows.size(); i++) {
            TabShow tabShow = tabShows.get(i);
            addViewSpecialSale(inflater, paramsLL, tabShow);
        }
//        llMainView.addView(inflater.inflate(R.layout.fragment_home_tab_special_sale, null),paramsLL);
        llMainView.setWeightSum(weightSum);

        //// TODO: 15/11/4 replace this whith config because this method  is a waste of time
        tabShows.get(0).getButton().performClick();
    }


    private void addViewSpecialSale(LayoutInflater inflater, LinearLayout.LayoutParams paramsLL, TabShow tabShow) {

        ImageTextButton itBtnSpecialSale = (ImageTextButton) inflater.inflate(R.layout.fragment_home_tab_special_sale, null);
        itBtnSpecialSale.setTag(tabShow);
        tabShow.setButton(itBtnSpecialSale);
        llMainView.addView(itBtnSpecialSale, paramsLL);
        if (!TextUtils.isEmpty(tabShow.getName())) {
            itBtnSpecialSale.setText(tabShow.getName());
        }
        if (tabShow.getIconId() > 0) {
            itBtnSpecialSale.setImage(tabShow.getIconId());
        }
        itBtnSpecialSale.setOnClickListener(tabListener);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        indexFragment = null;
        marketFragment = null;

    }


    /**
     * 绘制Fragment到屏幕中间  如果已经添加到事务中，则进行显示和隐藏操作
     *
     * @param fragment 需要推入的Fragment
     */
    public void showMainFragment(Fragment fragment) {
        FragmentTransaction transaction = homeActivity.getSupportFragmentManager().beginTransaction();
//        transaction.setCustomAnimations(R.anim.fragments_transition_in, R.anim.fragments_transition_out);
        if (currentFragment == null) {
            transaction.add(R.id.main_tab_content, fragment);
        } else if (currentFragment != fragment) {
            if (!fragment.isAdded()) {
                transaction.hide(currentFragment).add(R.id.main_tab_content, fragment);
            } else {
                transaction.hide(currentFragment).show(fragment);
            }
        }
        transaction.commitAllowingStateLoss();
        this.currentFragment = fragment;
    }


    public View.OnClickListener tabListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            TabShow tabShow = (TabShow) v.getTag();
            v.setSelected(true);
            for (int i = 0; i < llMainView.getChildCount(); i++) {
                if (!v.equals(llMainView.getChildAt(i))) {
                    llMainView.getChildAt(i).setSelected(false);
                }
            }
            switch (tabShow.getIdentify()) {
                case ID_TAB_SAIL:
                    if (indexFragment == null || indexFragment.get() == null) {
                        indexFragment = new SoftReference<>(HomeFragment.newInstance());
                    }
                    showMainFragment(indexFragment.get());
                    break;
                case ID_TAB_MARKET:
                    if (marketFragment == null || marketFragment.get() == null) {
                        marketFragment = new SoftReference<>(OrderFragment.newInstance());
                    }
                    showMainFragment(marketFragment.get());
                    break;
                case ID_TAB_MINE:
                    if (mineFragment == null || mineFragment.get() == null) {
                        mineFragment = new SoftReference<>(MineFragment.newInstance());
                    }
                    showMainFragment(mineFragment.get());
                    break;
                case ID_TAB_CART:

                    break;
            }

        }
    };


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

        }
    }

    private ArrayList<TabShow> getTabShows() {
        ArrayList<TabShow> tabShows = new ArrayList<>();
        TypedArray main_tab_img = getResources().obtainTypedArray(R.array.main_list_tab_img);
        String[] main_tab_name = getResources().getStringArray(R.array.main_list_tab_name);
        for (int i = 0; i < main_tab_img.length(); i++) {
            TabShow tabShow = new TabShow();
            tabShow.setIconId(main_tab_img.getResourceId(i, 0));
            tabShow.setName(main_tab_name[i]);
            tabShow.setIdentify(ids[i]);
            tabShows.add(tabShow);
        }
        main_tab_img.recycle();
        return tabShows;
    }

    public void setCurrentTab(int i) {
        ((ImageTextButton)llMainView.getChildAt(i)).performClick();
    }
}
